package cn.aitrox.ry.app.web.controller.anno;

import cn.aitrox.ry.app.web.config.AppNacosProperties;
import cn.aitrox.ry.app.web.vo.anno.ultrasound.in.VideoInfoInVo;
import cn.aitrox.ry.app.web.vo.anno.ultrasound.in.VideoTraceInVo;
import cn.aitrox.ry.app.web.vo.anno.ultrasound.out.FrameUrlOutVo;
import cn.aitrox.ry.app.web.vo.anno.ultrasound.out.VideoFrameInfoOutVo;
import cn.aitrox.ry.bean.RespResult;
import cn.aitrox.ry.common.controller.BaseController;
import cn.aitrox.ry.enumtype.RespCodeEnum;
import cn.aitrox.ry.service.anno.dto.anno.ultrasound.video.VideoTraceInDto;
import cn.aitrox.ry.service.anno.feign.AnnoUltrasoundFeign;
import cn.aitrox.ry.service.config.enumtype.ImageTransferModeEnum;
import cn.aitrox.ry.service.image.dto.image.in.ImageQueryInDto;
import cn.aitrox.ry.service.image.dto.image.out.ImageInfoOutDto;
import cn.aitrox.ry.service.image.dto.video.VideoInfnDto;
import cn.aitrox.ry.service.image.entity.ImageMongoEntity;
import cn.aitrox.ry.service.image.enumtype.ImageGroupTypeEnum;
import cn.aitrox.ry.service.image.feign.ImageFeign;
import cn.aitrox.ry.service.oss.dto.FileRestoreInfoDto;
import cn.aitrox.ry.service.oss.dto.in.DowanloadUrlGetInDto;
import cn.aitrox.ry.service.oss.feign.OssFeign;
import cn.aitrox.ry.util.ArrayUtil;
import cn.aitrox.ry.util.JSONUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
public class AnnoUltrasoundController extends BaseController {

    @Autowired
    @Lazy
    private AnnoUltrasoundFeign annoUltrasoundFeign;

    @Autowired
    @Lazy
    private ImageFeign imageFeign;

    @Autowired
    private AppNacosProperties appNacosProperties;

    @Autowired
    @Lazy
    private OssFeign ossFeign;

    @PostMapping("/anno/ultrasound/video/trace")
    public RespResult videoTrace(@Validated @RequestBody VideoTraceInVo input) {
        return annoUltrasoundFeign.videoTrace(new VideoTraceInDto(input.getArId()));
    }


    @PostMapping("/anno/ultrasound/video/frame/info")
    public RespResult<VideoFrameInfoOutVo> videoInfo(@Validated @RequestBody VideoInfoInVo input) {
        ImageQueryInDto imageQueryInDto = new ImageQueryInDto(Arrays.asList(input.getSeriesUid()), ImageGroupTypeEnum.SERIES_IMAGE_TRANSFER, Arrays.asList(ImageTransferModeEnum.VIDEO_FRAME_EXTRACT), null, true);
        RespResult<List<ImageInfoOutDto>> respResult = imageFeign.query(imageQueryInDto);
        if (!respResult._isOk()) {
            return RespResult.secByError(RespCodeEnum.ERROR.getCode(), "查询影像信息失败");
        }
        List<ImageInfoOutDto> imageInfoOutDtoList = respResult.getData();
        if (ArrayUtil.isEmpty(imageInfoOutDtoList)) {
            return RespResult.secByError(RespCodeEnum.NOT_EXIST.getCode(), "序列未跑视频分割");
        }
        ImageInfoOutDto imageInfoOutDto = imageInfoOutDtoList.get(0);
        if (null == imageInfoOutDto.getImageInfo() || ArrayUtil.isEmpty(imageInfoOutDto.getImageList())) {
            return RespResult.secByError(RespCodeEnum.NOT_EXIST.getCode(), "序列未跑视频分割");
        }

        String info = imageInfoOutDto.getImageInfo().getInfo();
        VideoInfnDto videoInfnDto = JSONUtil.fromJson(info, VideoInfnDto.class);

        // 如果是单帧的dcm，设置默认的视频长度以及帧率都为1
        if (videoInfnDto.getVideoFrames() == 1) {
            videoInfnDto.setVideoFrameRate(1f);
            videoInfnDto.setLengthInTime(1L);
        }

        // 如果视频长度大于60秒，则不支持标注
        if (null != appNacosProperties.getAnnoMaxVideoFrames() && videoInfnDto.getVideoFrames() > appNacosProperties.getAnnoMaxVideoFrames()) {
            return RespResult.secByError(RespCodeEnum.ERROR.getCode(), "视频帧数超过标注限制");
        }

        List<String> keyList = imageInfoOutDto.getImageList().stream().map(ImageMongoEntity::getKey).collect(Collectors.toList());
        RespResult<List<FileRestoreInfoDto>> fileInfoRespResult = ossFeign.urlGet(new DowanloadUrlGetInDto(keyList, appNacosProperties.getMaskUrlWanExpire(), appNacosProperties.getStorageType()));
        Map<String, String> urlMap = fileInfoRespResult.getData().stream().collect(Collectors.toMap(FileRestoreInfoDto::getResourceKey, FileRestoreInfoDto::getUrlWan));

        List<FrameUrlOutVo> frameUrls = imageInfoOutDto.getImageList().stream().filter(x -> !"zip".equalsIgnoreCase(x.getFileType())).map(x -> new FrameUrlOutVo(x.getNumber(), urlMap.get(x.getKey()))).collect(Collectors.toList());
        ImageMongoEntity zipImage = imageInfoOutDto.getImageList().stream().filter(x -> "zip".equalsIgnoreCase(x.getFileType())).findFirst().orElse(null);
        if (!fileInfoRespResult._isOk()) {
            return RespResult.secByError(RespCodeEnum.ERROR.getCode(), "查询影像下载地址失败");
        }

        Collections.sort(frameUrls);

        VideoFrameInfoOutVo outVo = new VideoFrameInfoOutVo();
        outVo.setFramesUrls(frameUrls);
        outVo.setFramesZipUrl(urlMap.get(zipImage.getKey()));
        outVo.setTotalFrame(videoInfnDto.getVideoFrames());
        outVo.setImageWidth(videoInfnDto.getImageWidth());
        outVo.setImageHeight(videoInfnDto.getImageHeight());
        outVo.setFrameRate(videoInfnDto.getVideoFrameRate().intValue());
//
//        VideoFrameInfoOutVo outVo = new VideoFrameInfoOutVo();
//        outVo.setFramesZipUrl(appNacosProperties.getVideoFrameZipUrl());
//        outVo.setTotalFrame(appNacosProperties.getVideoTotalFrames());
//        outVo.setImageWidth(appNacosProperties.getVideoImageWidth());
//        outVo.setImageHeight(appNacosProperties.getVideoImageHeight());
//        outVo.setFrameRate(appNacosProperties.getVideoFrameRate());

        return RespResult.ok(outVo);
    }

}
